package com.lon.over.ui.fragment;

import android.graphics.Rect;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lon.over.R;
import com.lon.over.base.BaseFragment;
import com.lon.over.model.domain.Categories;
import com.lon.over.model.domain.HomePagerContent;
import com.lon.over.presenter.ICategoryPresenter;
import com.lon.over.presenter.impl.CategoryPresenterImpl;
import com.lon.over.ui.adapter.HomePageContentAdapter;
import com.lon.over.ui.adapter.LopperPagerAdapter;
import com.lon.over.ui.custom.TbNestedScrollView;
import com.lon.over.utils.Constants;
import com.lon.over.utils.SizeUtils;
import com.lon.over.utils.ToastUtils;
import com.lon.over.view.ICategoryPagerCallback;

import java.util.List;

import butterknife.BindView;

/**
 * author: ctl | 陈泰龙
 * 创建时间: 2022/4/23
 * Describe:
 */
public class HomePagerFragment extends BaseFragment implements ICategoryPagerCallback {

    private ICategoryPresenter mCategoryPresenter;
    private int mMaterialId;
    private HomePageContentAdapter mContentAdapter;
    private LopperPagerAdapter mLopperPagerAdapter;

    public static HomePagerFragment newInstance(Categories.DataBean category) {
        HomePagerFragment homePagerFragment = new HomePagerFragment();
        Bundle bundle = new Bundle();
        bundle.putString(Constants.KEY_HOME_PAGER_TITLE, category.getTitle());
        bundle.putInt(Constants.KEY_HOME_PAGER_MATERIAL_ID, category.getId());
        homePagerFragment.setArguments(bundle);
        return homePagerFragment;
    }

    @BindView(R.id.home_pager_content_list)
    public RecyclerView mContentList;

    @BindView(R.id.looper_pager)
    public ViewPager mLooperPager;

    @BindView(R.id.page_part_title)
    public TextView partTitle;

    @BindView(R.id.looper_point_container)
    public LinearLayout looperPointContainer;

    @BindView(R.id.home_pager_parent)
    public LinearLayout homePagerParent;

    @BindView(R.id.home_pager_header_container)
    public LinearLayout homeHeaderContainer;

    @BindView(R.id.home_page_nested_scroller)
    public TbNestedScrollView homePageNestedScroller;

    @BindView(R.id.home_pager_fresh)
    public TwinklingRefreshLayout tkRefreshLayout;

    @Override
    protected void initView(View rootView) {
        //设置适配器
        mContentList.setLayoutManager(new LinearLayoutManager(getContext()));
        mContentList.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                outRect.top = 8;
                outRect.bottom = 8;
                outRect.left = 8;
                outRect.right = 8;
            }
        });
        //创建适配器
        mContentAdapter = new HomePageContentAdapter();
        //设置内容适配器
        mContentList.setAdapter(mContentAdapter);
        //创建轮播图适配器
        mLopperPagerAdapter = new LopperPagerAdapter();
        //设置轮播图适配器
        mLooperPager.setAdapter(mLopperPagerAdapter);
        //设置上下滑动Refresh相关配置
        tkRefreshLayout.setEnableRefresh(false);
        tkRefreshLayout.setEnableLoadmore(true);
    }

    @Override
    protected int getRootViewId() {
        return R.layout.fragment_home_pager;
    }

    @Override
    protected void initPresenter() {
        mCategoryPresenter = CategoryPresenterImpl.getInstance();
        mCategoryPresenter.registerViewCallback(this);
    }

    @Override
    protected void initListener() {
        homePagerParent.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                int headerHeight = homeHeaderContainer.getMeasuredHeight();
                homePageNestedScroller.setHeaderHeight(headerHeight);
                int measuredHeight = homePagerParent.getMeasuredHeight();
                LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) mContentList.getLayoutParams();
                layoutParams.height = measuredHeight;
                mContentList.setLayoutParams(layoutParams);
                if (measuredHeight != 0) {
                    homePagerParent.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }
            }
        });

        mLooperPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                //切换指示器
                if (mLopperPagerAdapter.getDataSize() == 0) {
                    return;
                }
                int targetPosition = position % mLopperPagerAdapter.getDataSize();
                updateLooperIndicator(targetPosition);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        tkRefreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                // 加载更多相关逻辑
                if (mCategoryPresenter != null) {
                    mCategoryPresenter.loadMore(mMaterialId);
                }
            }
        });
    }

    /**
     * 切换指示器
     *
     * @param targetPosition
     */
    private void updateLooperIndicator(int targetPosition) {
        for (int i = 0; i < looperPointContainer.getChildCount(); i++) {
            View point = looperPointContainer.getChildAt(i);
            if (i == targetPosition) {
                point.setBackgroundResource(R.drawable.shape_indicator_point_selected);
            } else {
                point.setBackgroundResource(R.drawable.shape_indicator_point_normal);
            }
        }
    }

    @Override
    protected void loadData() {
        Bundle arguments = getArguments();
        String title = arguments.getString(Constants.KEY_HOME_PAGER_TITLE);
        mMaterialId = arguments.getInt(Constants.KEY_HOME_PAGER_MATERIAL_ID);
        if (mCategoryPresenter != null) {
            mCategoryPresenter.getContentByCategoryId(mMaterialId);
        }
        if (partTitle != null) {
            partTitle.setText(title);
        }
    }

    @Override
    public void onContentLoad(List<HomePagerContent.DataBean> content) {
        //数据回传
        mContentAdapter.setData(content);
        setUpState(State.SUCCESS);
    }


    @Override
    public int getCateGoryId() {
        return mMaterialId;
    }

    @Override
    public void onLading() {
        setUpState(State.LOADING);
    }

    @Override
    public void onError() {
        setUpState(State.ERROR);
    }

    @Override
    public void onEmpty() {
        setUpState(State.EMPTY);
    }

    @Override
    public void onLoaderMoreError() {
        if (tkRefreshLayout != null) {
            tkRefreshLayout.finishLoadmore();
        }
        ToastUtils.toastShow("网络异常，请检查网络设置 ~ ~");
    }

    @Override
    public void onLoaderMoreEmpty() {
        if (tkRefreshLayout != null) {
            tkRefreshLayout.finishLoadmore();
        }
        ToastUtils.toastShow("没有更多数据了哦 ~ ~");
    }

    @Override
    public void onLoaderMoreLoaded(List<HomePagerContent.DataBean> content) {
        mContentAdapter.addContentData(content);
        if (tkRefreshLayout != null) {
            tkRefreshLayout.finishLoadmore();
        }
        ToastUtils.toastShow("更新了" + content.size() + "条数据");
    }

    @Override
    public void onLooperListLoaded(List<HomePagerContent.DataBean> content) {
        mLopperPagerAdapter.setData(content);
        int dx = (Integer.MAX_VALUE / 2) % content.size();
        int targetCenterPosition = (Integer.MAX_VALUE / 2) - dx;
        // 设置中间点，可无限滚动
        mLooperPager.setCurrentItem(targetCenterPosition);
        looperPointContainer.removeAllViews();
        // 添加滚动点
        for (int i = 0; i < content.size(); i++) {
            View point = new View(getContext());
            int size = SizeUtils.dip2px(getContext(), 8);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(size, size);
            layoutParams.leftMargin = SizeUtils.dip2px(getContext(), 5);
            layoutParams.rightMargin = SizeUtils.dip2px(getContext(), 5);
            point.setLayoutParams(layoutParams);
            if (i == 0) {
                point.setBackgroundResource(R.drawable.shape_indicator_point_selected);
            } else {
                point.setBackgroundResource(R.drawable.shape_indicator_point_normal);
            }
            looperPointContainer.addView(point);
        }
    }

    @Override
    protected void release() {
        if (mCategoryPresenter != null) {
            mCategoryPresenter.unregisterViewCallback(this);
        }
    }
}
